<?php
/**
 * 字段过滤
 *
 * @author xyma
 *
 */
class FilterHelper
{
	/**
	  HTML元素白名单
	  */
	static $white_list = 'b|blockquote|br|code|div|em|h1|h2|h3|h4|h5|h6|hr|i|li|ol|p|pre|s|span|sub|sup|strike|strong|ul|a|style|img'; 
	/**
	  HTML元素属性黑名单,正则語法
	  */
	static $black_attr = 'class|id|on\w{2,}';

	/**
	 过滤全部html
	 */
	public static function strip($str) {
		return strip_tags($str);
	}
	
	/**
	 HTML转义
	 */
	public static function invert($str) {
		return htmlspecialchars($str, ENT_NOQUOTES, 'utf-8', false);
	}
	
	/**
	  采用HTML白名单，过滤敏感tags和属性
	  */
	public static function sanitize($str)
	{
		if(false===stripos(self::$white_list, 'style')){
			$str = preg_replace('~<(style)[^>]*>.*?</\1>~is', '', $str);
		}
		if(false===stripos(self::$white_list, 'script')){
			$str = preg_replace('~<(script)[^>]*>.*?</\1>~is', '', $str);
		}

		static $wl;
		if(!$wl){
			$wl = join('', array_map( array(__CLASS__, '_quote'), 
									explode('|', self::$white_list)));
		}
		$str = strip_tags($str, $wl);
		$str = preg_replace_callback('~<\w+\s+([^>]+)>~isx', 
									array(__CLASS__, '_sani_cb'), $str);
		return $str;
	}

	private static function _quote($str){ return "<{$str}>"; }

	private static function _sani_cb($m){
		return preg_replace('~
				('.self::$black_attr.')
				\s*=\s*
				(
					(["\']) .*? \3
					|
					\w+
				)
				~isx', '', $m[0]);
	}
	
}
?>
